package com.kf.conf;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.kf.pojo.User;
import com.kf.service.UserService;

//自定义realm
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;

	//执行授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("执行授权");
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//A：：：手工添加权限
//		info.addStringPermission("user:add");
		
		//数据库查询获取权限
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		System.out.println("获取user："+user);
		info.addStringPermission(user.getPerms());
		return info;
	}
	
	//执行认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行认证");
		String principal = (String) token.getPrincipal();
		//A::::::::假设数据库用户名密码
/*		String name="1";
		String pwd = "1";
		//用户名不存在
				if(!principal.equals(name)){
					//底层返回UnknownAccountException报错
					return null;
				}
		return new SimpleAuthenticationInfo("", pwd, "");*/
		
		
		//B：：：：：：：：：数据库查询
		User user = userService.getByUserName(principal);
		if(null==user){
			return null;
		}
		System.out.println("查询数据库用户======");
		
		return new SimpleAuthenticationInfo(user, user.getPassword(), "");
	}

}
